<template>
<h2>婚礼纪</h2>
<van-form @submit="onSubmit">
  <van-cell-group inset>
    <van-field
      v-model="user.username"
      name="username"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, msg: '请输入用户名' }]"
    />
    <van-field
      v-model="user.phone"
      name="phone"
      label="电话号码"
      placeholder="电话号码"
      :rules="[{ required: true, msg: '请输入电话号码' }]"
    />
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      提交
    </van-button>
  </div>
</van-form>

<div style="text-align: center">
    未注册的手机号将自动注册
</div>
</template>

<script setup>
import api from "@/api";
import { showFailToast, showSuccessToast } from "vant";
import 'vant/lib/toast/style'
import { useRouter } from "vue-router";
import { ref } from "vue"
const user=ref({})

const router=useRouter()

const onSubmit = async (values) => {
  try {
    const res = await api.postReq("/login", values);
    const result = res.data;
    // console.log(result.data)

    if (result === undefined) {
      showFailToast("接口返回格式异常");
      return;
    }
    if (result.code === 1) {
      // console.log(result.data)
      // console.log(result.data.token)
      // 确保data和token存在再存储
      if (result.data && result.data.token) {
        localStorage.setItem("myToken", result.data.token);
        localStorage.setItem("user", JSON.stringify(result.data));
        showSuccessToast(result.msg || "登录成功");
        router.push("/");
      } else {
        showFailToast("登录信息不完整");
      }
    } else {
      showFailToast(result.msg || "登录失败，请重试");
    }
  } catch (error) {
    console.error("登录请求失败:", error);
    showFailToast("网络异常，请检查网络连接");
  }
};
</script>
<style scoped>
</style>
